<?php 
/**
 * Youdian Content Management System
 * Copyright (C) YoudianSoft Co.,Ltd (http://www.youdiancms.com). All rights reserved. 
 */
class YdUpgrade{
	//升级文件格式：patch_4_3_15_20130606.zip(patch_主版本_次版本_修订号_日期固定为8位)
	//次版本号只能是一位
	//升级文件列表
	private $_upgradeUrl = 'http://www.youdiancms.com/cmsupgrade';
	private $_list = array();
	private $_latestVersion = null;
	private $_latestDate = null;
	private $_needUpgrade = null;
	private $_cachePath = null;
	
	function __construct($currentVersion){
		//$str = @file_get_contents($this->_upgradeUrl.'/index.html');
		$str = "";
		if( strlen($str) > 20 ){
			preg_match_all("/patch_[\w_]+\.zip/", $str,  $all);
		}
		if( empty($all[0]) ) return;
		$pathlist = $all[0];
		//获取可用版本===========================================
		foreach ($pathlist as $k=>$v){
			$d = $this->validate($v);
			if( $d && $this->compare($d[0], $currentVersion) > 0 ){
				$this->_list[] = array('version'=>$d[0], 'date'=>$d[1], 'filename'=>$v);
			}
		}
		$n = count( $this->_list  );
		if($n < 1) return;
		//===================================================
		$this->_cachePath = RUNTIME_PATH.'upgrade';
		$this->_latestVersion = $this->_list[$n-1]['version'];
		$this->_latestDate = $this->_list[$n-1]['date'];
		$this->_needUpgrade = $this->compare($this->_latestVersion, $currentVersion) > 0 ? true : false;
	}
	
	//版本比较v1>v2 返回1；v1=v2 返回0；v1<v2 返回-1；
	function compare($v1, $v2){
		$a1 = explode('.', $v1);
		$a2 = explode('.', $v2);
		if( empty($a1[2]) ) $a1[2] = 0;
		if( empty($a2[2]) ) $a2[2] = 0;
		
		$n1 = $a1[0]*100 + $a1[1]*10 + $a1[2];
		$n2 = $a2[0]*100 + $a2[1]*10 + $a2[2];
		if( $n1 > $n2 ) return 1;
		if( $n1 == $n2 ) return 0;
		if( $n1 < $n2 ) return -1;
	}
	
	//有效性检查，并返回版本号和日期
	function validate($zipName){
		//patch_4_3_15_20130606.zip
		$zipName = str_ireplace('.zip', '', trim($zipName));
		$arr = explode('_', $zipName);
		$n = count($arr);
		if( $n == 5){
			$version = $arr[1].'.'.$arr[2].'.'.$arr[3];
			$date = substr($arr[4], 0, 4).'-'.substr($arr[4], 4, 2).'-'.substr($arr[4], 6, 2);
			return array($version, $date);
		}else{
			return false;
		}
	}
	
	
	//获取最新版本
	function getLatestVersion(){
		return $this->_latestVersion;
	}
	
	//获取最后发布日期
	function getLatestDate(){
		return $this->_latestDate;
	}
	
	//判断是否是需要升级
	function needUpgrade(){
		return $this->_needUpgrade;
	}
	
	//根据当前版本获取正确的升级文件列表
	function getList(){
		return $this->_list;
	}
	
	//开始升级
	function start(){
		@set_time_limit(0);
		import('ORG.Util.PclZip');
		import('ORG.Io.Dir');
		$dir = new Dir();
		//若缓存文件夹不存在，则创建
		if( !file_exists($this->_cachePath) ){
			@mkdir( $this->_cachePath  );
		}
		//依次下载，解压, 拷贝覆盖，更新数据库
		foreach ($this->_list as $v){
			$url = $this->_upgradeUrl.'/'.$v['filename'];
			$savePath = $this->_cachePath.'/'.$v['filename']; //保存路径
			$unzipPath = $this->_cachePath.'/'.basename($v['filename'], '.zip'); //解压路径
			$sqlFile = $unzipPath.'/sql/update.sql';
			
			@file_put_contents($savePath,  @file_get_contents($url) );  //下载zip压缩包
			$zip = new PclZip($savePath);
			if( $zip->extract(PCLZIP_OPT_PATH, $unzipPath, PCLZIP_OPT_REPLACE_NEWER) == 0 ){ 
				return false;  //解压失败
			}
			
			//更新数据库
			$this->updateDb( $sqlFile );
			
			//拷贝覆盖原程序目录
			$srcPath = $unzipPath.'/upgrade';
			$dstPath = './';
			$dir->copyDir($srcPath, $dstPath);
		}
		return true;
	}
	
	//更新数据库
	function updateDb($sql){
		if( !file_exists($sql) ) return true;
		$content = @file_get_contents($sql);
		//防止产生乱码，将读取的文字转换为utf-8编码
		$content = iconv("gb2312", "utf-8//IGNORE",$content);
		$db = M();
		$sqlList = sql_split($content);
		foreach ($sqlList as $query) {
			$query = trim($query);
			if ($query) {
				@$db->execute($query);
			}
		}
		return true;
	}
	
	//删除所有升级临时文件
	function deleteAll(){
		if(is_dir( $this->_cachePath )){
			@deldir( $this->_cachePath  );
		}
	}
}